package com.ms.controller;

import com.ms.entity.User;
import com.ms.entity.Volunteer;
import com.ms.service.inter.VolunteerService;
import com.ms.utils.SimpleTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 志愿者控制器 - 处理志愿者相关的HTTP请求
 * 包括志愿者报名、查询等功能
 */
@RestController
@RequestMapping("/api/volunteer")
@CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求
public class VolunteerController {

    @Autowired
    private VolunteerService volunteerService;

    /**
     * 志愿者报名接口
     *
     * @param volunteer 志愿者报名信息
     * @param request   HTTP请求
     * @return 报名结果
     */
    @PostMapping("/apply")
    public ResponseEntity<Map<String, Object>> applyVolunteer(@RequestBody Volunteer volunteer, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;

            // 修改：直接设置 Integer userID
            volunteer.setUserID(currentUser.getUserID());

            // 检查用户是否已经申请过志愿者
            Volunteer existingApplication = volunteerService.findByUserId(currentUser.getUserID());
            // 如果已存在申请记录，只有在待审核或已通过状态下才禁止重复申请
            if (existingApplication != null && 
                ("pending".equals(existingApplication.getStatus()) || 
                 "approved".equals(existingApplication.getStatus()))) {
                result.put("success", false);
                if ("pending".equals(existingApplication.getStatus())) {
                    result.put("message", "您已经提交过志愿者申请，请等待审核");
                } else {
                    result.put("message", "您已经是志愿者，无需重复申请");
                }
                return ResponseEntity.badRequest().body(result);
            }

            // 设置申请状态为"待审核"
            volunteer.setStatus("pending");
            volunteer.setApplyTime(new Date());

            // 保存志愿者申请信息
            // 如果之前有被拒绝的申请记录，先删除再重新创建
            if (existingApplication != null) {
                volunteerService.deleteByUserId(currentUser.getUserID());
            }
            volunteerService.save(volunteer);

            result.put("success", true);
            result.put("message", "志愿者申请提交成功，请等待审核");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "申请失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取当前用户的志愿者申请信息
     *
     * @param request HTTP请求
     * @return 志愿者申请信息
     */
    @GetMapping("/my-application")
    public ResponseEntity<Map<String, Object>> getMyApplication(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;

            Volunteer application = volunteerService.findByUserId(currentUser.getUserID());
            if (application == null) {
                //  修改：返回 success: true 但 application: null，而不是错误
                result.put("success", true);
                result.put("application", null);
                result.put("message", "您还没有提交志愿者申请");
                return ResponseEntity.ok(result);
            }

            result.put("success", true);
            result.put("application", application);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取申请信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 取消志愿者申请
     *
     * @param request HTTP请求
     * @return 取消结果
     */
    @DeleteMapping("/cancel")
    public ResponseEntity<Map<String, Object>> cancelApplication(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;

            Volunteer application = volunteerService.findByUserId(currentUser.getUserID());
            if (application == null) {
                result.put("success", false);
                result.put("message", "您还没有提交志愿者申请");
                return ResponseEntity.badRequest().body(result);
            }

            // 只有pending状态的申请可以取消
            if (!"pending".equals(application.getStatus())) {
                result.put("success", false);
                result.put("message", "只有待审核的申请可以取消");
                return ResponseEntity.badRequest().body(result);
            }

            volunteerService.deleteByUserId(currentUser.getUserID());

            result.put("success", true);
            result.put("message", "志愿者申请已取消");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "取消申请失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取所有志愿者申请（管理员功能）
     *
     * @param request HTTP请求
     * @return 所有志愿者申请列表
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllApplications(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 这里可以添加管理员权限检查
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            List<Volunteer> applications = volunteerService.findAll();
            result.put("success", true);
            result.put("applications", applications);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取申请列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新志愿者申请状态（管理员功能）
     *
     * @param applicationId 申请ID
     * @param statusData    状态数据
     * @param request       HTTP请求
     * @return 更新结果
     */
    @PutMapping("/status/{applicationId}")
    public ResponseEntity<Map<String, Object>> updateApplicationStatus(
            @PathVariable Integer applicationId, // 修改：改为 Integer
            @RequestBody Map<String, String> statusData,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        String status = statusData.get("status");
        String reviewNotes = statusData.get("reviewNotes");

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 修改：参数改为 Integer
            Volunteer application = volunteerService.findById(applicationId);
            if (application == null) {
                result.put("success", false);
                result.put("message", "申请记录不存在");
                return ResponseEntity.badRequest().body(result);
            }

            application.setStatus(status);
            if (reviewNotes != null) {
                application.setReviewNotes(reviewNotes);
            }

            volunteerService.update(application);

            result.put("success", true);
            result.put("message", "申请状态更新成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新状态失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 根据用户ID获取志愿者信息
     * @param userId 用户ID
     * @param request HTTP请求
     * @return 志愿者信息
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getVolunteerByUserId(
            @PathVariable Integer userId,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 获取志愿者信息
            Volunteer volunteer = volunteerService.findByUserId(userId);
            if (volunteer != null) {
                result.put("success", true);
                result.put("volunteer", volunteer);
            } else {
                result.put("success", false);
                result.put("message", "未找到志愿者信息");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}